//
//  PaperCollectionView.m
//  ZYOnlineSchool
//
//  Created by 毕武侠 on 2017/3/9.
//  Copyright © 2017年 bwx. All rights reserved.
//

#import "PaperCollectionView.h"
#import "PaperCollectionViewCell.h"
#import "PaperCollectionReusableView.h"
#import "PaperCollectionFootView.h"

@interface PaperCollectionView () <cellDidActionDelegate>
{
    NSMutableDictionary *dict;
}
@property (nonatomic, strong)UIAlertView *alertView;
@end

@implementation PaperCollectionView

- (instancetype)initForPaperCollectionView {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    self = [super initWithFrame:CGRectMake(0, kNavigationBarHeight + 40, SCREEN_WIDTH, SCREEN_HEIGHT - kNavigationBarHeight - 40) collectionViewLayout:layout];
    [self setupConfigureWith:layout];
    return self;
}

- (void)setupConfigureWith:(UICollectionViewFlowLayout *)layout {
    self.minLineSpace = 0;
    self.minInteritemSpace = 0;
    self.edgeInsets = UIEdgeInsetsZero;
    self.pagingEnabled = YES;
    
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    [self initstance];
    
    // 注册cell
    [self registerClass:[PaperCollectionViewCell class] forCellWithReuseIdentifier:@"PaperCollectionViewCellID"];
    
    // 注册head
    [self registerClass:[PaperCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"PaperCollectionReusableViewID"];
    
    // 注册foot
    [self registerClass:[PaperCollectionFootView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"PaperCollectionFootViewID"];
}

#pragma mark - collectionView Head Delegate

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    
    PaperModuleModel *firstModel = self.sourceData[section];
    if (firstModel.showModule == YES) {
        return  CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT - kNavigationBarHeight - 40);
    } else {
        return CGSizeZero;
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    if (self.showToolCard == NO || section != self.sourceData.count - 1) {
        return CGSizeZero;
    } else {
        return CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT - kNavigationBarHeight - 40);
    }
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if ([kind isEqualToString:UICollectionElementKindSectionFooter]) {
        PaperCollectionFootView *footView = (PaperCollectionFootView *)[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"PaperCollectionFootViewID" forIndexPath:indexPath];
        footView.showSendView = self.showSendView;
        footView.showTitleView = self.showCardTitleView;
        footView.sourceData = self.sourceData;
        footView.selectBlock = ^(NSIndexPath *indexPath) {
            [self moveToIndexPath:indexPath];
        };
        footView.sendBlock = ^(NSMutableDictionary *dic) {
            dict = dic;
            [self showalert];
//            if ([self.didDatagate respondsToSelector:@selector(collectionView:didActionIndexPath:infoData:)]) {
//                [self.didDatagate collectionView:self didActionIndexPath:nil infoData:@{@"action" : @"send", @"data" : dic}];
//            }
        };
        return footView;
    } else if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        PaperModuleModel *firstModel = self.sourceData[indexPath.section];
        PaperCollectionReusableView *headView = nil;
        headView = (PaperCollectionReusableView *)[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"PaperCollectionReusableViewID" forIndexPath:indexPath];
        [headView bindModel:firstModel];
        return headView;
    }
    return nil;
}
- (void)showalert{
    if (self.sourceData.count == 0) {                // 没有数据，直接退出
//        [self.exitSignal sendNext:nil];
    } else {
        __block NSUInteger selectIndex = 0;
        __block NSUInteger allIndex = 0;
        
        [self.sourceData enumerateObjectsUsingBlock:^(PaperModuleModel *moduleModel, NSUInteger idx, BOOL * _Nonnull stop) {
            allIndex += moduleModel.module_question.count;
            
            [moduleModel.module_question enumerateObjectsUsingBlock:^(PaperBaseModel * model, NSUInteger idx, BOOL * _Nonnull stop) {
                if ((model.ques_model == 0 || model.ques_model == 2) && model.index != NSNotFound) {
                    selectIndex++;
                } else if ((model.ques_model == 1 || model.ques_model == 3) && model.index > 0) {
                    selectIndex++;
                }
            }];
        }];
        
        if (selectIndex == 0) {
            //[self.exitSignal sendNext:nil];    // 有数据，但未作答，直接退出
            self.alertView.message = [NSString stringWithFormat:@"您尚有%ld题未答，确定交卷吗？", allIndex - selectIndex];
            [self.alertView show];
            return;

        } else {
            if (selectIndex == allIndex) {
//                self.alertView.message = @"您已全部作答完成，确定要退出本次答题？";
                [self sendData];
                return;
            } else {
                self.alertView.message = [NSString stringWithFormat:@"您尚有%ld题未答，确定交卷吗？", allIndex - selectIndex];
                [self.alertView show];
                return;
            }
            
        }
    }

}
- (void)sendData{
    if ([self.didDatagate respondsToSelector:@selector(collectionView:didActionIndexPath:infoData:)]) {
        [self.didDatagate collectionView:self didActionIndexPath:nil infoData:@{@"action" : @"send", @"data" : dict}];
    }
}

- (UIAlertView *)alertView {
    if (_alertView == nil) {
        _alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    }
    return _alertView;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex) {
        //[self.exitSignal sendNext:nil];         // 有数据，作答了几道题，但仍然退出
        [self sendData];
    }
}


#pragma mark  collectionView delegate dataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.sourceData.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    PaperModuleModel *firstModel = self.sourceData[section];
    return firstModel.module_question.count;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return  CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT - kNavigationBarHeight - 40);
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    PaperModuleModel *firstModel = self.sourceData[indexPath.section];
    PaperAnswerModel *model = firstModel.module_question[indexPath.row];
    
    PaperCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:
                                    @"PaperCollectionViewCellID" forIndexPath:indexPath];
    if (cell == nil) {
        cell = [[PaperCollectionViewCell alloc] init];
    }

    cell.indexPath = indexPath;
    cell.actionDelegate = self;
    [cell bindModel:model];
    return cell;
}

- (void)moveToIndexPath:(NSIndexPath *)indexPath {
    [self scrollToItemAtIndexPath:indexPath
                 atScrollPosition:UICollectionViewScrollPositionNone
                         animated:YES];
}

- (void)moveToCurrentHeadAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewLayoutAttributes *attributes = [self layoutAttributesForItemAtIndexPath:indexPath];
    CGRect rect = attributes.frame;
    [self setContentOffset:CGPointMake(rect.origin.x - SCREEN_WIDTH, 0) animated:YES];
}

- (void)moveToNextHeadAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewLayoutAttributes *attributes = [self layoutAttributesForItemAtIndexPath:indexPath];
    CGRect rect = attributes.frame;
    [self setContentOffset:CGPointMake(rect.origin.x + SCREEN_WIDTH, 0) animated:YES];
}


- (void)moveToFootView {
    [self setContentOffset:CGPointMake(self.contentSize.width - SCREEN_WIDTH, 0) animated:YES];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
